package org.ruizhijie.run;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.util.Enumeration;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ruizhijie.config.SystemConfig;
import org.ruizhijie.config.TopicQueue;
import org.ruizhijie.i.impl.OutComSubcriberImpl;

public class OutCom implements Runnable, SerialPortEventListener {
	private Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

	// 检测系统中可用的通讯端口类
	private CommPortIdentifier cpi;
	// RS232串口
	private SerialPort serialPort;

	public OutCom(TopicQueue tq,String inCom,String outCom) {
		this.cpi = getCommPort(outCom);

		if (this.cpi == null) {
			log.error(outCom + "获取串口失败, 程序退出");
			System.exit(0);
			return;
		}
		System.err.println(outCom + "获取串口成功");

		try {
			serialPort = (SerialPort) cpi.open("SerialPort_" + outCom, 2000);
			// 设置串口通讯参数:波特率，数据位，停止位,校验方式
			serialPort.setSerialPortParams(SystemConfig.baudRate,
					SystemConfig.dataBits,
					SystemConfig.stopBits,
					SystemConfig.parity);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
		new OutComSubcriberImpl(tq, inCom, serialPort);
	}

	@SuppressWarnings("unchecked")
	private CommPortIdentifier getCommPort(String serialNumber) {
		Enumeration<CommPortIdentifier> portList = CommPortIdentifier
				.getPortIdentifiers();
		while (portList.hasMoreElements()) {
			CommPortIdentifier cpi = portList.nextElement();
			// 判断是否是串口
			if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL
					&& serialNumber.equals(cpi.getName())) {
				return cpi;
			}
		}
		return null;
	}

	// 实现接口SerialPortEventListener中的方法 读取从串口中接收的数据
	@Override
	public void serialEvent(SerialPortEvent event) {
	}

	public void closeSerialPort() {
		// uniqueInstance.serialPort.close();
	}

	@Override
	public void run() {
	}
}
